//定义剧照相关接口
const express = require("express");
const router = express.Router();
//引入mysql连接池
const pool = require("../utils/db");
//引入joi表单验证模块
const Joi = require("joi");
//引入响应对象模块
const Response = require("../utils/Response");
//通过movie_id查询剧照
//接口地址
router.get("/movie-thumbs/movieid", (req, resp) => {
  let { movie_id } = req.query;
  //表单验证
  let schema = Joi.object({
    movie_id: Joi.string().required(),
  });
  let { error, value } = schema.validate(req.query);
  if (error) {
    resp.send(Response.error(400, error));
    return;
  }
  let sql = "select * from movie_thumb where movie_id= ?";

  pool.query(sql, [movie_id], (error, result) => {
    if (error) {
      resp.send(Response.error(500, error));
      throw err;
    }
    resp.send(Response.ok(result));
  });
});
//删除剧照接口
//接口地址/movie-thumb/del
router.post("/movie-thumb/del", (req, resp) => {
  let { id } = req.body;
  //表单验证
  let schema = Joi.object({
    id: Joi.string().required(),
  });
  let { error, value } = schema.validate(req.body);
  if (error) {
    resp.send(Response.error(400, error));
    return;
  }
  //执行删除业务
  let sql = "delete from movie_thumb where id = ?";
  pool.query(sql, [id], (error, result) => {
    if (error) {
      resp.send(Response.error(500, error));
      throw error;
    }
    resp.send(Response.ok());
  });
});
//添加剧照接口
//接口地址/movie-thumb/add
router.post("/movie-thumb/add", (req, resp) => {
  let { movie_id, url } = req.body;
  //表单验证
  let schema = Joi.object({
    movie_id: Joi.string().required(),
    url: Joi.string().required(),
  });
  let { error, value } = schema.validate(req.body);
  if (error) {
    resp.send(Response.error(400, error));
    return;
  }
  //表单验证通过，执行添加操作
  let sql = "insert into movie_thumb (movie_id,url) values (?,?)";
  pool.query(sql, [movie_id, url], (error, result) => {
    if (error) {
      resp.send(Response.error(500, error));
      throw err;
    }
    resp.send(Response.ok());
  });
});

//将Router接口导出
module.exports = router;
